class Observer {
  constructor(data) {
    this.walk(data)
  }

  walk (data) {
    if(!data || typeof data !== 'object') return
    Object.keys(data).forEach(key => {
      this.defineReactive(data, key, data[key])
      if(typeof data[key] === 'object') {
        this.walk(data[key])
      }
    })
  }

  defineReactive (obj, key, val) {
    const self = this
    // 给每个data中的key创建一个收集依赖的实例对象
    const dep = new Dep()
    Object.defineProperty(obj, key, {
      configurable: true,
      enumerable: true,
      get () {
        // 访问数据时，就收集该数据的watcher
        Dep.target && dep.addSub(Dep.target)
        return val
      },
      set (newVal) {
        if (newVal === val) return
        val = newVal
        self.walk(newVal)
        // 发送通知
        dep.nodtify()
      }
    })
  }
}